package com.dong.boot.config;

import com.alibaba.fastjson.JSON;
import com.dong.boot.model.Hr;
import com.dong.boot.model.RespBean;
import com.dong.boot.service.HrService;
import com.dong.boot.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    HrService userService;

    @Autowired
    MyFilter myFilter;
    @Autowired
    MyDecision myDecision;

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()//开启配置处理授权的请求
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(myFilter);
                        o.setAccessDecisionManager(myDecision);
                        return o;
                    }
                })
                .anyRequest()//所有的请求都要遵循此配置
                .authenticated()//所有的请求都要有权限
                .and()
                .formLogin() //开始配置表单登陆相关
                .loginProcessingUrl("/doLogin") //登陆接口
                .loginPage("/login")
                .successHandler(new AuthenticationSuccessHandler() { //登陆成功之后的处理
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter w = resp.getWriter();
                        Hr hr = (Hr) auth.getPrincipal();
                        hr.setPassword(null);
                        RespBean ok = RespBean.ok("登陆成功", hr);
                        String s = JSON.toJSONString(ok);
                        w.write(s);
                        w.flush();
                        w.close();
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() { //登陆失败的处理
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter w = resp.getWriter();
                        RespBean error = RespBean.error("登陆失败");
                        if (e instanceof LockedException){
                            error.setMsg("账户被锁定");
                        }else if (e instanceof CredentialsExpiredException){
                            error.setMsg("密码过期");
                        }else if (e instanceof AccountExpiredException){
                            error.setMsg("账户过期");
                        }else if (e instanceof BadCredentialsException){
                            error.setMsg("用户名或密码不正确");
                        }else if (e instanceof DisabledException){
                            error.setMsg("账户不可用");
                        }
                        String s = JSON.toJSONString(error);
                        w.write(s);
                        w.flush();
                        w.close();
                    }
                })
                .permitAll()//登陆之后允许所有请求访问
                .and()
                .logout() //登出的相关配置
                .logoutSuccessHandler(new LogoutSuccessHandler() {//登出成功的处理
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter w = resp.getWriter();
                        RespBean ok = RespBean.ok("登出成功");
                        String s = JSON.toJSONString(ok);
                        w.write(s);
                        w.flush();
                        w.close();
                    }
                })
                .permitAll()
                .and()
                .csrf().disable()
                .exceptionHandling()
                //没有认证时，在这里处理结果，不要重定向
                .authenticationEntryPoint((req, resp, authException) -> {
                            resp.setContentType("application/json;charset=utf-8");
                            resp.setStatus(401);
                            PrintWriter out = resp.getWriter();
                            RespBean respBean = RespBean.error("访问失败!");
                            if (authException instanceof InsufficientAuthenticationException) {
                                respBean.setMsg("请求失败，请联系管理员!");
                            }
                            out.write(new ObjectMapper().writeValueAsString(respBean));
                            out.flush();
                            out.close();
                        }
                );;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/login");
    }
}
